package cn.chinaunicom.sdsi.frm.workflow.cmd;

import java.util.Map;

import org.activiti.engine.impl.interceptor.Command;
import org.activiti.engine.impl.interceptor.CommandContext;
import org.activiti.engine.impl.persistence.entity.ExecutionEntity;
import org.activiti.engine.impl.pvm.process.ActivityImpl;
import org.activiti.engine.impl.pvm.process.ProcessDefinitionImpl;

import cn.chinaunicom.sdsi.frm.workflow.common.WorkflowConstants;

/**
 * from lemonOA 实现自由流跳转，业务数据恢复需业务自行处理
 * 
 * @author liyh
 */
public class JumpToActivityCmd implements Command<Object> {
	/**
	 * 自带属性
	 */
	private String activityId;
	private String executionId;
	private String jumpOrigin;

	/**
	 * 流程变量
	 */
	private Map<String, Object> vars;

	public JumpToActivityCmd(String executionId, String activityId, Map<String, Object> vars) {
		this(executionId, activityId, WorkflowConstants.COMPLETED_TYPE_FREE, vars);
	}

	public JumpToActivityCmd(String executionId, String activityId, String jumpOrigin, Map<String, Object> vars) {
		this.activityId = activityId;
		this.executionId = executionId;
		this.jumpOrigin = jumpOrigin;
		this.vars = vars;
	}

	public Object execute(CommandContext commandContext) {

		// 取当前处理环节实体并加入处理的相关变量
		ExecutionEntity executionEntity = commandContext.getExecutionEntityManager().findExecutionById(executionId);
		// executionEntity.setVariableLocal("handleType",
		// vars.get("handleType"));
		// 20170227借鉴咖啡兔代码调整自由流，且处理方式不再存为任务变量
		vars.remove("handleType");
		executionEntity.setVariables(vars);
		executionEntity.destroyScope(jumpOrigin);

		// 据实体取到其所在流程定义并获取跳转目标实体
		ProcessDefinitionImpl processDefinition = executionEntity.getProcessDefinition();
		ActivityImpl activity = processDefinition.findActivity(activityId);

		executionEntity.executeActivity(activity);

		return executionEntity;
	}
}
